package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.ChannelMapper;
import com.heima.admin.service.ChannelService;
import com.heima.model.admin.dtos.ChannelDto;
import com.heima.model.admin.pojos.Channel;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ChannelServiceImpl extends ServiceImpl<ChannelMapper, Channel> implements ChannelService {
    @Autowired
    private ChannelMapper channelMapper;

    /**
     * 频道分页查找
     *
     * @param channelDto
     * @return
     */
    @Override
    public ResponseResult pageList(ChannelDto channelDto) {
        if (null == channelDto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        IPage page = new Page<>(channelDto.getPage(),channelDto.getSize());
        LambdaQueryWrapper<Channel> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Channel::getCreatedTime);
        if (StringUtils.isNotEmpty(channelDto.getName())){
            wrapper.like(Channel::getName,channelDto.getName());
        }
        if (channelDto.getStatus() == 0 || channelDto.getStatus() == 1){
            wrapper.eq(Channel::getStatus,channelDto.getStatus());
        }
        channelMapper.selectPage(page, wrapper);
        ResponseResult responseResult =new PageResponseResult(channelDto.getPage(),channelDto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 删除频道
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteById(Integer id) {
        Channel channel = channelMapper.selectById(id);
        if (channel.getStatus()){
            return ResponseResult.errorResult(AppHttpCodeEnum.CHANNEL_ACTIVE);
        }
        channelMapper.deleteById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
